package vip.xiaonuo.megvii.captures.handle.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import vip.xiaonuo.megvii.captures.handle.ActivePushHandleImpl;
import vip.xiaonuo.megvii.captures.model.AlertsEntity;
import vip.xiaonuo.megvii.captures.model.base.AlertEvent;
import vip.xiaonuo.modular.megviialertdata.entity.MegviiAlertData;
import vip.xiaonuo.modular.megviialertdata.service.MegviiAlertDataService;
import vip.xiaonuo.modular.megviipushdata.entity.MegviiPushData;
import vip.xiaonuo.modular.megviipushdata.service.MegviiPushDataService;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * 预警数据处理
 */
@Service
public class AlertsHandlerService extends PushDataBaseHandler implements ActivePushHandleImpl<AlertsEntity> {

    @Resource
    private MegviiAlertDataService alertDataService;

    @Override
    public void handle(@NotNull MegviiPushData data) {
        try{
            String text = data.getValue();
            AlertsEntity entity = JSON.parseObject(text,AlertsEntity.class);

            // 业务数据转换与保存
            this.saveData(entity);

            // TODO 事件预警

            // 保存原始数据处理结果
            data.setStatus(1);
            pushDataService.saveOrUpdate(data);
        }catch (Exception e){
            data.setFailReason(ExceptionUtils.getMessage(e));
            data.setStatus(2);
            pushDataService.saveOrUpdate(data);
        }
    }

    @Override
    public void saveData(AlertsEntity entity) {
        MegviiAlertData data = new MegviiAlertData();

        Long imgId  = this.saveImg(entity.getPhoto_crop(),fileService);
        Long fullImgId = this.saveImg(entity.getPhoto(),fileService);
        data.setImgId(imgId);
        data.setFullImgId(fullImgId);

        data.setDeviceId(entity.getDevice_id());
        data.setChannelName(entity.getStream_name());

        data.setAlertTime(new Date(entity.getRecv_ts()));

        List<AlertEvent> events = entity.getAlert_events();

        for (AlertEvent event : events) {
            data.setId(null);
            // 目标类型 什么物体
            data.setTargetType( event.getTarget().getTargetTypeDesc());

            // 区域类型 在哪里
            data.setAreaType(event.getAreaTypeDesc());

            // 警戒类型 触发了什么警戒
            data.setAlertorType(event.getAlertorTypeDesc());

            alertDataService.save(data);
        }
    }
}
